<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Attachment;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Illuminate\Support\Facades\Storage;

class AttachmentController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Attachment(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('url')->link(function ($value) {
                return Storage::url($value);
            });
            $grid->column('ext');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter$filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Attachment(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('ext');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Attachment(), function (Form $form) {
            $form->display('id');
            $form->text('title');
            $form->file('url')->uniqueName()->rules('required|mimes:jpg,bmp,png,jpeg,pdf,xls,doc|max:2048', [
                'required' => '须传入文件',
                'mimes' => '文件类型须为：jpg,bmp,png,jpeg,pdf,xls,doc 这几种类型',
                'max' => '文件最大为2M',
            ]);
            $form->hidden('ext')->default('');
            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form) {
                $data = $form->input();
                list($filename, $ext) = explode('.', $data['url']);
                $form->ext = $ext;
            });
        });
    }
}
